package com.shamar.blog.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;

/**
 * @author zhy
 * @date 2020/1/2 下午6:11
 * @descrption 配置导入工具
 **/
public final class ClassLoaderUtil {

    private static Logger logger = LoggerFactory.getLogger(ClassLoaderUtil.class);

    // class path
    private static String classPath = "";

    // loader
    private static ClassLoader loader = Thread.currentThread().getContextClassLoader();

    private ClassLoaderUtil() {
    }

    // get class path
    static {
        if (loader == null) {
            loader = ClassLoader.getSystemClassLoader();
        }
        try {
            URL url = loader.getResource("");
            // get class path
            File f = new File(url.toURI());
            classPath = f.getAbsolutePath();
            classPath = URLDecoder.decode(classPath, "utf-8");
            // 如果是jar包内的，则返回当前路径
            if (classPath.contains(".jar!")) {
                classPath = System.getProperty("user.dir");
                addCurrentWorkingDir2Classpath(classPath);
            }
        } catch (Exception e) {
            classPath = System.getProperty("user.dir");
            addCurrentWorkingDir2Classpath(classPath);
        }
    }

    /**
     * only support 1.7 or higher
     * http://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java
     */
    private static void addCurrentWorkingDir2Classpath(String path2Added) {
        // Add the conf dir to the classpath
        // Chain the current thread classloader
        URLClassLoader urlClassLoader = null;
        try {
            urlClassLoader = new URLClassLoader(new URL[]{new File(path2Added).toURI().toURL()},
                    loader);
            // Replace the thread classloader - assumes
            // you have permissions to do so
            Thread.currentThread().setContextClassLoader(urlClassLoader);
        } catch (Exception e) {
            logger.error("urlClassLoader load class error", e);
        }finally {
            try {
                if(null != urlClassLoader){
                    urlClassLoader.close();
                }
            }catch (Exception e){
                logger.error("urlClassLoader close error", e);
            }

        }
    }

    public static String getClassPath() {
        return classPath;
    }

    public static ClassLoader getLoader() {
        return loader;
    }
}
